//
//  AppDelegate.m
//  shise
//
//  Created by 毛志鹏 on 14/12/17.
//  Copyright (c) 2014年 MZP. All rights reserved.
//

#import "AppDelegate.h"
#import "HomeViewController.h"
#import "FoundViewController.h"
#import "MoreViewController.h"
#import "MyViewController.h"
//#import <ShareSDK/ShareSDK.h>
//#import "WeiboSDK.h"
#import "WeiboSDK.h"
#import "UIColor+AddColor.h"

@interface AppDelegate ()<UITabBarControllerDelegate,WeiboSDKDelegate>

@end

@implementation AppDelegate
//4e15960e3ea7      8cb1da6ac0dea5a22b9289d842ea7723
//1867821658       829675132c9a7e897f07d83a992b5059
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
     [NSThread sleepForTimeInterval:1];
    
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:@"1867821658"];
    
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    self.window.backgroundColor = [UIColor whiteColor];
    [_window release];
    
    
    
    //指定为根视图
    UITabBarController *tabbarVC = [[UITabBarController alloc]init];
    self.window.rootViewController = tabbarVC;
    
    //点击变颜色的设置
    tabbarVC.tabBar.tintColor = [UIColor colorFromHexCode:@"#efb336"];
    //框颜色的设置
    tabbarVC.tabBar.barTintColor = [[UIColor alloc]initWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:0.5];
    //[[UIColor alloc]initWithRed:50.0/255.0 green:100.0/255.0 blue:55.0/255.0 alpha:0.5];/墨绿

    //[[UIColor alloc]initWithRed:200.0/255.0 green:255.0/255.0 blue:239.0/255.0 alpha:0.5];/蓝色
    //[[UIColor alloc]initWithRed:180.0/255.0 green:200.0/255.0 blue:255.0/255.0 alpha:0.5];/藕荷色

    //指定代理
    tabbarVC.delegate = self;
    [tabbarVC release];
    
    
    //主页设置
    HomeViewController *homeVC = [[HomeViewController alloc]init];
    homeVC.title = @"首页";
    homeVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"首页" image:[UIImage imageNamed:@"hhhh64.png"] tag:100];
    UINavigationController *naviHome = [[UINavigationController alloc]initWithRootViewController:homeVC];
    naviHome.navigationBar.barTintColor  =[UIColor whiteColor];
    [homeVC release];
    
    //发现页面
    FoundViewController *foundVC = [[FoundViewController alloc]init];
    foundVC.title = @"发现";
    foundVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"发现" image:[UIImage imageNamed:@"iconfont-creative.png"] tag:101];
    UINavigationController *naviFound = [[UINavigationController alloc]initWithRootViewController:foundVC];
    //naviFound.navigationBar.barStyle = UIBarStyleBlack;
    naviFound.navigationBar.barTintColor  =[UIColor whiteColor];

    [foundVC release];
    
    
    
    //更多页面
    MoreViewController *moreVC =[[MoreViewController alloc]init];
    moreVC.title = @"更多";
    moreVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"更多" image:[UIImage imageNamed:@"iconfont-liwu.png"] tag:102];
    UINavigationController *naviMore = [[UINavigationController alloc]initWithRootViewController:moreVC];
    //naviMore.navigationBar.barStyle = UIBarStyleBlack;
    naviMore.navigationBar.barTintColor = [UIColor whiteColor];
    [moreVC release];
    
    
    
    //我的页面
    MyViewController *myVC = [[MyViewController alloc]init];
    myVC.title = @"我的";
    myVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"我的" image:[UIImage imageNamed:@"iconfont-wozhengchang.png"] tag:103];
    UINavigationController *naviMy = [[UINavigationController alloc]initWithRootViewController:myVC];
    //naviMy.navigationBar.barStyle = UIBarStyleBlack;
    naviMy.navigationBar.barTintColor = [UIColor whiteColor];
    [myVC release];
    
    
    
    NSArray *arr = [NSArray arrayWithObjects:naviHome,naviFound,naviMore,naviMy, nil];

    
    [naviHome release];
    [naviFound release];
    [naviMore release];
    [naviMy release];
    
    tabbarVC.viewControllers = arr;
    
    
    return YES;
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        NSString *title = NSLocalizedString(@"发送结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode, NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil),response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
               // [alert show];
        [alert release];
        
        
        int i = (int)response.statusCode;
        
        if (i == 0) {
            //延时调用  一秒以后执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"分享成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
                [alertView release];
                

            });

            
        }

    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSString *title = NSLocalizedString(@"认证结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.userId: %@\nresponse.accessToken: %@\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode,[(WBAuthorizeResponse *)response userID], [(WBAuthorizeResponse *)response accessToken],  NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
//                [alert show];
        [alert release];
        NSLog(@"vvvvvvvv%@", self.wbtoken);
        
        NSString * str = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@",self.wbCurrentUserID,self.wbtoken];
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSLog(@"-----%@", str);
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
        request.HTTPMethod = @"GET";
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//                        NSLog(@"%@", result);
            
//            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:result,@"key", nil];
            
        }];
        int i = (int)response.statusCode;
        if (i == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"登陆成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];
            //通知中心，传值
            [[NSNotificationCenter defaultCenter]postNotificationName:@"suibian" object:@"随便" userInfo:response.userInfo];
            

        }
        
        
    }
    else if ([response isKindOfClass:WBPaymentResponse.class])
    {
        NSString *title = NSLocalizedString(@"支付结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.payStatusCode: %@\nresponse.payStatusMessage: %@\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode,[(WBPaymentResponse *)response payStatusCode], [(WBPaymentResponse *)response payStatusMessage], NSLocalizedString(@"响应UserInfo数据", nil),response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WeiboSDK handleOpenURL:url delegate:self];
    
}

- (void)dealloc
{
    [_window release];
    [super dealloc];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


//- (BOOL)application:(UIApplication *)application
//      handleOpenURL:(NSURL *)url
//{
//    return [ShareSDK handleOpenURL:url
//                        wxDelegate:self];
//}
//
//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation
//{
//    return [ShareSDK handleOpenURL:url
//                 sourceApplication:sourceApplication
//                        annotation:annotation
//                        wxDelegate:self];
//}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
